package com.talent.core.protocol.websocket.zk;

import com.google.gson.Gson;
import com.talent.core.protocol.websocket.NettyServer;
import org.apache.curator.framework.CuratorFramework;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;

/**
 * @ClassName：ZkRegister
 * @Author: hszhou
 * @Date: 2024/12/9 18:31
 * @Description: 必须描述类做什么事情, 实现什么功能
 */
public class ZkRegister {

    public static void registerNettyServer(String nodeNode,String ip,int port) throws Exception {
        CuratorFramework zkClient = CuratorConfig.getClient();

        String path = "/"+nodeNode;
        Stat stat = zkClient.checkExists().forPath(path);
        if(null==stat){
            zkClient.create()
                    //递归创建
                    .creatingParentsIfNeeded()
                    .withMode(CreateMode.PERSISTENT)
                    .forPath(path);

        }
        NettyServer node = new NettyServer();
        node.setIp(ip);
        node.setPort(port);

        Gson gson = new Gson();
        String nodeJson =gson.toJson(node);

        zkClient.create()
                .withMode(CreateMode.EPHEMERAL_SEQUENTIAL)
                .forPath(path+"/node-",nodeJson.getBytes());

    }

    public static void dealOnlineCount(NettyServer nettyServer,Integer count) throws Exception {

        CuratorFramework client = CuratorConfig.getClient();
        String path = "service-list";
        List<String> children = client.getChildren().forPath(path);
        Gson gson = new Gson();
        for (String child : children) {
            String nodePath =path+"/"+child;
            String nodeVal=new String(client.getData().forPath(nodePath));

            NettyServer pendingNode = gson.fromJson(nodeVal, NettyServer.class);

            if(pendingNode.getIp().equals(nettyServer.getIp()) &&
                    (pendingNode.getPort().intValue()==nettyServer.getPort().intValue())){
                pendingNode.setOnline(pendingNode.getOnline()+count);
                String json = gson.toJson(pendingNode);
                client.setData().forPath(nodePath,json.getBytes());
            }
        }
    }

    public static void incrementOnlineCount(NettyServer nettyServer) throws Exception {
        dealOnlineCount(nettyServer,1);
    }

    public static void decrementOnlineCount(NettyServer nettyServer) throws Exception {
        dealOnlineCount(nettyServer,1);
    }


    public static String getLocalIp() throws UnknownHostException {
        InetAddress localHost = InetAddress.getLocalHost();
        String hostAddress = localHost.getHostAddress();
        return hostAddress;
    }
}
